package com.liuhangs.learning.crowd.webui.security.service.impl;

import com.liuhangs.learning.crowd.webui.bean.auth.Role;
import com.liuhangs.learning.crowd.webui.bean.auth.User;
import com.liuhangs.learning.crowd.webui.mapper.AdminUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**用户信息服务类
 * @author 11757
 * @DATE 2020/6/18
 */
@Service("userSecurityServiceImpl")
public class UserSecurityServiceImpl implements UserDetailsService {

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException
    {
        User user = adminUserMapper.queryUserRoleInfoByAcc(account);
        if(null == user) {
            return null;
        }
        org.springframework.security.core.userdetails.User userDetails =
                new org.springframework.security.core.userdetails.User(user.getAccount(),user
                        .getPassword(),getAuthorities(user.getRoles()));
        return userDetails;
    }

    /**
     * 获取用户角色
     * @param roles
     * @return
     */
    private Collection<GrantedAuthority> getAuthorities(List<Role> roles){
        List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
        roles.stream().map(t -> authList.add(new SimpleGrantedAuthority(t.getRoleName
                ()))).collect(toList());
        return authList;
    }


}
